<template>
	<view class="page__content">
		<view class="page__content__main">
			<view class="ble__card">
				<view class="ble__card__top">
					<text>已配对设备</text>
				</view>

				<view class="ble__card__content">
					<template v-if="isLinkDevice.length">

						<u-cell v-for="item in isLinkDevice" :key="item.deviceId">
							<template #title>
								<view class="x-f">
									<view style="color: #333;margin-left: 10px;">
										<text>{{item.aliasName || item.name}}</text>
									</view>
								</view>
							</template>

							<template #label>
								<text v-if="item.connected"
									style="margin-left: 10px;color: #05bc4f;font-size: 12px;">已连接</text>
								<text v-else style="margin-left: 10px;color: #999;font-size: 12px;">未连接</text>
							</template>

							<template #value>
								<view @click="handlerClickToLink(item)">
									<u-icon name="setting-fill" color="#333" size="24"></u-icon>
								</view>
							</template>
						</u-cell>
					</template>

					<template v-else>
						<view class="x-c" style="height: 80px;font-size: 12px;color: #999;">
							<text>暂无已配对设备！</text>
						</view>
					</template>

				</view>
			</view>

			<view class="ble__card">
				<view class="ble__card__top">
					<text>可用设备</text>
				</view>

				<view class="ble__card__content">
					<u-cell v-for="item in deviceList" :key="item.deviceId">
						<template #title>
							<view class="x-f">
								<volume :num="item.RSSI"></volume>

								<view style="color: #333;margin-left: 10px;">
									<text>{{item.aliasName || item.name}}</text>
								</view>
							</view>
						</template>
						<template #value>
							<button type="primary" size="mini" @click="connectDevice(item)">
								<text style="font-size: 12px;">连接</text>
							</button>
						</template>
					</u-cell>
				</view>
			</view>

		</view>

		<view class="page__content__bottom x-ec">

			<button v-if="!isDiscovering" class="btn CommonBtnSize" type="primary" @click="startScan">开始扫描</button>

			<template v-else>

				<button class="btn CommonBtnSize" type="primary" @click="refreshScan">刷新列表</button>

				<button class="btn CommonBtnSize" type="warn" @click="stopScan">停止扫描</button>
			</template>
		</view>
	</view>
</template>

<script setup lang="ts" name="page-link-bluetooth">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	import volume from "@/st_qms/components/page_index/signal"

	// 已配对设备
	// let isLinkDevice = ref<any>([]);


	let choiceDeviceInfo = reactive<any>({});

	// 获取选中的临时设备数据
	const baseParam = uni.$utils.deepClone(qmsStore.DeviceLinkConfig.tempData_device
		.deviceInfo) || {};

	Object.assign(choiceDeviceInfo, baseParam);

	// 获取已配对数据
	let isLinkDevice = computed<any>(() => {
		return Object.values(bluetoothStore.connectedDevices).filter(item => {
			return item.config.BluetoothProtocol == choiceDeviceInfo.BluetoothProtocol;
		})
	});

	// 点击已配对设备
	const handlerClickToLink = (data : any) => {
		uni.navigateTo({
			url: "/st_qms/page_device/page_device_link" + "?deviceId=" + data.deviceId
		})
	};


	const isDiscovering = computed(() => {
		return bluetoothStore.adapterState.discovering
	});

	// 扫描出来的数据
	let deviceList = ref<any>([]);
	// 点击连接按钮
	const connectDevice = (deviceObj : any) => {
		uni.$utils.$bluetooth.connectDevice(deviceObj, choiceDeviceInfo, () => {
			// 删除查询列表中已连接的蓝牙信息
			deviceList.value = deviceList.value.filter(item => {
				return deviceObj.deviceId != item.deviceId;
			})
		})


	}
	const deviceConfig = reactive<any>({
		showPopup: false,
		formMenus: [{
			name: '取消配对',
			value: '',
			icon: 'reload',
			show: true,
		}, {
			name: '设置别名',
			value: '',
			icon: 'reload',
			show: true,
		},],
		setName: false,
		changeName: "",
		tempDeviceInfo: {},
		bluetoothType: false, // 蓝牙适配器是否开启
		RSSI: 0,


		findDevice: false, // 是否查询到设备
		showLoading: false,
		scanTimer: null
	})

	let deviceMap = ref<any>({})

	// 开启扫描
	const startScan = () => {
		// 清除可能存在的旧计时器，避免重复计时
		if (deviceConfig.scanTimer) {
			clearInterval(deviceConfig.scanTimer);
			deviceConfig.scanTimer = null;
		}
		// 重置扫描状态
		deviceConfig.showLoading = true; // 显示加载中
		deviceConfig.findDevice = false; // 标记是否在本轮5秒内找到设备
		let _currentSecond = 0; // 当前计时秒数
		uni.$utils.$bluetooth.startDiscovery((devices : any) => {
			// console.log('原始扫描设备列表:', devices);

			// 处理弹层开启时的设备过滤逻辑
			if (deviceConfig.showPopup) {
				const currentDeviceId = deviceConfig.tempDeviceInfo?.deviceId;
				if (devices.length) {
					const targetDevice = devices.find(item => item.deviceId === currentDeviceId);
					if (targetDevice) {
						deviceConfig.RSSI = targetDevice.RSSI;
						deviceConfig.findDevice = true;
						deviceConfig.showLoading = false;
					}
				}
			};

			// 关键：批量处理设备别名并去重
			let list = [...deviceList.value];
			// 从蓝牙管理器获取内存中的别名映射表（一次获取，批量使用）
			const aliasMap = uni.$utils.$bluetooth.aliasMap;
			for (let i = 0; i < devices.length; i++) {
				let dev = devices[i];
				// 1. 绑定别名（从内存映射表直接获取，O(1)复杂度）
				const alias = aliasMap[dev.deviceId];
				if (alias) {
					dev['aliasName'] = alias;
				} else {
					dev['aliasName'] = dev.name || dev.localName || '未知设备';
				}

				// 2. 原有去重逻辑（保持不变，但基于处理后的dev）
				if (deviceMap.value[dev.deviceId] !== undefined) {
					let index = deviceMap.value[dev.deviceId];
					list.splice(index, 1, dev);
				} else {
					list.push(dev);
					deviceMap.value[dev.deviceId] = list.length - 1;
				}
			};

			deviceList.value = list;

		});

		deviceConfig.scanTimer = setInterval(() => {
			_currentSecond++; // 每秒累加
			if (_currentSecond >= 5) {
				if (deviceConfig.findDevice) {
					// 情况1：本轮5秒内找到设备 → 重置计时，进入下一轮5秒
					_currentSecond = 0; // 重置秒数
					deviceConfig.findDevice = false; // 重置标记（等待下一轮判断）
					console.log("找到设备，进入下一轮5秒扫描");
				} else {
					// 情况2：本轮5秒内未找到设备 
					deviceConfig.scanTimer = null;
					deviceConfig.showLoading = false; // 隐藏加载中
					deviceConfig.findDevice = false; // 标记未找到
					_currentSecond = 0;
				}

			}
		}, 1000);
	};

	// 停止扫描
	const stopScan = () => {

		// 情况2：本轮5秒内未找到设备 → 停止扫描
		clearInterval(deviceConfig.scanTimer); // 清除计时器
		uni.$utils.$bluetooth.stopDiscovery();

	};
	// 刷新扫描列表
	const refreshScan = () => {
		deviceMap.value = {};
		deviceList.value = [];
	}




	onLoad(async () => {
		await uni.$utils.$bluetooth.openBluetooth();


		startScan();
	});

	onUnload(() => {
		stopScan();
	})
</script>

<style lang="scss">
	.page__content {
		height: 100%;
		background-color: #f9f9f9;

		&__main {
			padding: 15px;

			.ble__card {
				padding: 15px;
				border-radius: 15px;

				&__top {
					padding: 8px 0;
					font-size: 14px;
					color: #999;
				}

				&__content {
					background-color: #fff;
					color: #333;
					// min-height: 100px;
					border-radius: 15px;
					overflow: hidden;
				}
			}


		}

		&__bottom {
			padding: 15px;

			.btn {
				margin-left: 10px;
			}
		}
	}
</style>